package com.bxx.service.impl;

import com.bxx.dao.*;
import com.bxx.pojo.*;
import com.bxx.service.RoleModuleService;
import com.bxx.service.RolePermissionService;
import com.bxx.service.RoleService;
import com.bxx.util.DateParse;
import com.bxx.util.PageUtil;
import com.bxx.util.R;
import com.bxx.vo.TreeNodeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class RoleServiceImpl implements RoleService {

    //注入角色持久层对象
    @Autowired
    private RoleDao roleDao;
    //注入权限持久层对象
    @Autowired
    private PermissionDao permissionDao;
    //注入模块持久层对象
    @Autowired
    private ModuleDao moduleDao;
    //注入角色模块业务层对象
    @Autowired
    private RoleModuleService roleModuleService;
    //注入角色权限业务层对象
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public PageUtil<Role> listRoles(PageUtil<Role> pageUtil) {
        List<Role> roles = roleDao.listRoles(pageUtil);
        Integer count = roleDao.getCount(pageUtil);

        pageUtil.setData(roles);
        pageUtil.setCount(count);
        return pageUtil;
    }

    @Override
    public R insertRole(Role role) {
        role.setRoleId(UUID.randomUUID().toString());
        role.setCreateTime(DateParse.parseTimeStamp(new Date()));
        Integer r = roleDao.insertRole(role);
        if(r > 0){
            return R.ok("添加成功");
        }else {
            return R.error("添加失败");
        }
    }

    @Override
    public R deleteRole(String roleId) {
        Integer r = roleDao.deleteRole(roleId);
        if(r > 0){
            return R.ok("删除成功");
        }else {
            return R.error("删除失败");
        }
    }

    @Override
    public R updateRole(Role role) {
        role.setUpdateTime(DateParse.parseTimeStamp(new Date()));
        Integer r = roleDao.updateRole(role);
        if(r > 0){
            return R.ok("修改成功");
        }else {
            return R.error("修改失败");
        }
    }

    //==================获取角色拥有的模块和权限转换成树结构======================
    @Override
    public List<TreeNodeVO> getRoleHaveModuleAndPermissionConvertTree(String roleId) {

        //获取全部模块和权限信息
        List<Module> modules = moduleDao.listModules();
        List<Permission> permissions = permissionDao.listPermissions();

        //将全部模块和权限数据转换成树结构
        List<TreeNodeVO> treeNodeVOs = convertModulePermissionTree(modules, permissions);

        //获取角色拥有的模块和权限信息
        List<RoleModule> roleModules = roleModuleService.getRoleModulesByRoleId(roleId);
        List<RolePermission> rolePermissions = rolePermissionService.getRolePermissionsByRoleId(roleId);

        List<Object> idList = new ArrayList<Object>();
        for (RoleModule roleModule:roleModules) {
            idList.add(roleModule.getModuleId());
        }
        for (RolePermission rolePermission:rolePermissions) {
            idList.add(rolePermission.getPermissionId());
        }

        //根据角色拥有的模块和权限设置树节点选中
        for (Object id:idList) {
            treeNodeVOs = setTreeNodeChecked(id, treeNodeVOs);
        }

        return treeNodeVOs;
    }

    @Override
    public List<TreeNodeVO> convertModulePermissionTree(List<Module> modules, List<Permission> permissions) {
        //新建树节点数组
        List<TreeNodeVO> treeNodeVOs = new ArrayList<TreeNodeVO>();
        for (Module module : modules) {
            //判断是否是最外层模块
            if (module.getParentId() == 0){
                //查找子节点，返回带有子节点的父节点
                TreeNodeVO treeNodeVO = findChildren(module, modules, permissions);
                treeNodeVOs.add(treeNodeVO);
            }
        }
        return treeNodeVOs;
    }

    @Override
    public TreeNodeVO findChildren(Module parent, List<Module> modules, List<Permission> permissions) {
        //新建模块树节点
        TreeNodeVO treeNodeVO = new TreeNodeVO();
        treeNodeVO.setId(parent.getModuleId());
        treeNodeVO.setTitle("【模块】" + parent.getModuleName());
        //模块节点标识
        treeNodeVO.setField("module");

        //查找模块拥有的权限
        for (Permission permission:permissions) {
            //如果权限的模块名称等于模块的名称，则为该模块的权限
            if (permission.getPermissionModule().equals(parent.getModuleName())){
                if (treeNodeVO.getChildren() == null){
                    treeNodeVO.setChildren(new ArrayList<TreeNodeVO>());
                }
                //新建权限树节点
                TreeNodeVO child = new TreeNodeVO();
                child.setId(permission.getPermissionId());
                child.setTitle("【权限】" + permission.getPermissionName());
                //模块节点标识
                child.setField("permission");
                treeNodeVO.getChildren().add(child);
            }
        }

        //查找父模块拥有的子模块
        for (Module module:modules) {
            //如果模块的父id等于父节点的id，则为子模块
            if (module.getParentId().equals(parent.getModuleId())){
                if (treeNodeVO.getChildren() == null){
                    treeNodeVO.setChildren(new ArrayList<TreeNodeVO>());
                }
                //递归继续寻找子节点
                TreeNodeVO child = findChildren(module, modules, permissions);

                //将带有子节点的节点添加到父节点中
                treeNodeVO.getChildren().add(child);
            }
        }

        return treeNodeVO;
    }

    //=============================end============================
    @Override
    public List<TreeNodeVO> setTreeNodeChecked(Object id, List<TreeNodeVO> treeNodeVOs) {
        for (TreeNodeVO treeNodeVo:treeNodeVOs) {
            //如果传来的模块或者权限id等于当前遍历的节点id,并且子节点为空才设置循环中
            if(id.equals(treeNodeVo.getId()) && (treeNodeVo.getChildren() == null || treeNodeVo.getChildren().size() == 0)){
                //设置选中
                treeNodeVo.setChecked(true);
                //找到节点后退出循环
                break;
            }
            //如果有孩子节点
            if (treeNodeVo.getChildren() != null){
                //递归遍历孩子节点设置选中
                setTreeNodeChecked(id, treeNodeVo.getChildren());
            }
        }

        return treeNodeVOs;
    }

    //================给角色设置模块和权限==============
    @Override
    public R giveRoleSetModulesAndPermissions(String roleId, List<Integer> moduleIdList, List<String> permissionIdList) {

        //给角色设置模块
        R r = this.giveRoleSetModules(roleId, moduleIdList);
        //给角色设置权限
        R r1 = this.giveRoleSetPermissions(roleId, permissionIdList);

        return R.ok("操作成功！" + r.get("msg") + "," + r1.get("msg"));
    }


    /*案例：
    Owner 123
    Operation 2345
    Owner∪Operation 12345
    Owner∩Operation 23
    差异 145
    Add 45
    Del 1
     */
    @Override
    public R giveRoleSetModules(String roleId, List<Integer> moduleIdList) {
        //新建要给角色添加的模块id集合
        List<Integer> addModuleIdList = new ArrayList<Integer>();
        //新建要给角色删除的模块id集合
        List<Integer> delModuleIdList = new ArrayList<Integer>();
        //获取角色拥有的模块
        List<RoleModule> ownerModules = roleModuleService.getRoleModulesByRoleId(roleId);
        //提取角色拥有的模块id
        List<Integer> ownerModuleIdList = new ArrayList<Integer>();
        if(ownerModules != null && ownerModules.size() > 0){
            for (RoleModule roleModule : ownerModules) {
                ownerModuleIdList.add(roleModule.getModuleId());
            }
        }

        if(moduleIdList == null || moduleIdList.size() < 1){
            return R.error("模块id集合参数异常!");
        }

        //角色的模块id和传来的模块id求并集操作
        //模块id交集集合，初始化将传来的模块全部赋值给集合
        List<Integer> AllModuleIdList = new ArrayList<Integer>(moduleIdList);
        //遍历用户拥有的模块id
        for (Integer moduleId : ownerModuleIdList) {
            //如果交集集合中不包含角色拥有的模块id添加到集合中
            if(!(AllModuleIdList.contains(moduleId))){
                AllModuleIdList.add(moduleId);
            }
        }

        //遍历交集集合
        for (Integer moduleId:AllModuleIdList) {
            //如果角色拥有这个模块且操作集合中没有这个模块，则添加到删除集合中
            if(ownerModuleIdList.contains(moduleId) && !moduleIdList.contains(moduleId)){
                delModuleIdList.add(moduleId);
            }else if(!ownerModuleIdList.contains(moduleId) && moduleIdList.contains(moduleId)){
                //如果角色没有这个模块且操作集合中有这个模块，则添加到添加集合中
                addModuleIdList.add(moduleId);
            }
        }

        RoleModule roleModule = new RoleModule();
        roleModule.setRoleId(roleId);

        int delr = 0;
        int addr = 0;
        if(delModuleIdList.size() > 0){
            //执行删除
            for (Integer moduleId:delModuleIdList) {
                roleModule.setModuleId(moduleId);
                Integer r = roleModuleService.deleteRoleModuleByRoleIdAndModuleId(roleModule);
                if(r > 0){
                    delr += 1;
                }
            }
        }
        if(addModuleIdList.size() > 0){
            //执行添加
            for (Integer moduleId:addModuleIdList) {
                roleModule.setModuleId(moduleId);
                Integer r = roleModuleService.insertRoleModule(roleModule);
                if(r > 0){
                    addr += 1;
                }
            }
        }

        return R.ok("给用户添加了" + addr + "个模块，移除了" + delr + "个模块");

    }

    @Override
    public R giveRoleSetPermissions(String roleId, List<String> permissionIdList) {
        //新建要给角色添加的权限id集合
        List<String> addPermissionIdList = new ArrayList<String>();
        //新建要给角色删除的权限id集合
        List<String> delPermissionIdList = new ArrayList<String>();
        //获取角色拥有的权限
        List<RolePermission> ownerPermissions = rolePermissionService.getRolePermissionsByRoleId(roleId);
        //提取角色拥有的权限id
        List<String> ownerPermissionIdList = new ArrayList<String>();
        if(ownerPermissions != null && ownerPermissions.size() > 0){
            for (RolePermission rolePermission : ownerPermissions) {
                ownerPermissionIdList.add(rolePermission.getPermissionId());
            }
        }

        if(permissionIdList == null || permissionIdList.size() < 1){
            return R.error("权限id集合参数异常!");
        }

        //角色的权限id和传来的权限id求并集操作
        //权限id交集集合，初始化将传来的模块全部赋值给集合
        List<String> AllPermissionIdList = new ArrayList<String>(permissionIdList);
        //遍历用户拥有的模块id
        for (String permissionId : ownerPermissionIdList) {
            //如果交集集合中不包含角色拥有的模块id添加到集合中
            if(!(AllPermissionIdList.contains(permissionId))){
                AllPermissionIdList.add(permissionId);
            }
        }

        //遍历交集集合
        for (String permissionId:AllPermissionIdList) {
            //如果角色拥有这个权限且操作集合中没有这个权限，则添加到删除集合中
            if(ownerPermissionIdList.contains(permissionId) && !permissionIdList.contains(permissionId)){
                delPermissionIdList.add(permissionId);
            }else if(!ownerPermissionIdList.contains(permissionId) && permissionIdList.contains(permissionId)){
                //如果角色没有这个权限且操作集合中有这个权限，则添加到添加集合中
                addPermissionIdList.add(permissionId);
            }
        }

        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);

        int delr = 0;
        int addr = 0;
        if(delPermissionIdList.size() > 0){
            //执行删除
            for (String permissionId:delPermissionIdList) {
                rolePermission.setPermissionId(permissionId);
                Integer r = rolePermissionService.deleteRolePermissionByRoleIdAndPermissionId(rolePermission);
                if(r > 0){
                    delr += 1;
                }
            }
        }
        if(addPermissionIdList.size() > 0){
            //执行添加
            for (String permissionId:addPermissionIdList) {
                rolePermission.setPermissionId(permissionId);
                Integer r = rolePermissionService.insertRolePermission(rolePermission);
                if(r > 0){
                    addr += 1;
                }
            }
        }

        return R.ok("给用户添加了" + addr + "个权限，移除了" + delr + "个权限");
    }
}
